Converting enum to int in C#
Converting enum to int in C#
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
18-Aug-2023There are two ways to convert an enum to an int in C#:
ToInt()method.valueproperty.Using the
ToInt()methodThe
ToInt()method takes an enum as its parameter and returns the corresponding integer value. The following code converts an enum to an int:C#
In this code, the
ToInt()method is used to convert theColor.Redenum to an int. The result is the integer value 0, which is the underlying value of theColor.Redenum.Using the
valuepropertyThe
valueproperty of an enum returns the underlying integer value of the enum. The following code also converts an enum to an int:C#
In this code, the
valueproperty of theColor.Redenum is used to get the underlying integer value, which is 0.Which method you use to convert an enum to an int depends on your preference. The
ToInt()method is more explicit, as it explicitly specifies that you are converting the enum to an int. However, thevalueproperty is more concise and easier to read.